import time

import paho.mqtt.client as mqtt


def run():
    # 判断是否连接上mqtt服务器
    def on_connect(self, client, userdata, flags, rc):
        """连接回调函数"""
        if flags == 0:
            print("Connected to MQTT successfully!")
        else:
            print("Failed to connect, return code {0}".format(flags))

    # 订阅的主题中有新消息发布，则触发回调函数打印
    def on_message(client, userdata, msg):
        """消息回调函数"""
        # print(msg.topic + " " + ":" + msg.payload.decode())

    # 创建客户端实例对象，参数为回调API版本，客户端的ID
    client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2, client_id="python_mqtt")
    client.on_connect = on_connect  # 设置回调函数
    client.on_message = on_message  # 设置回调函数
    client.connect("192.168.16.220", 1883, 60)  # 连接服务器，参数(ip,端口,超时时间)
    client.subscribe("mqtt_esp32_project_01")  # 订阅"topic/aaa"主题
    client.loop_start()  # 开启线程，保持与服务器的连接

    time.sleep(0.5)
    while True:
        context = input("请输入你要发送的内容：")
        time.sleep(0.5)
        client.publish("mqtt_esp32_project_01", context, 0, True)  # 向"test"主题中发布context内容，QoS服务等级为0，True为指定消息要保留
        print(f"消息发送成功: {context}\n")
        time.sleep(0.5)


if __name__ == '__main__':
    run()
